package cn.tradewin.advisor.persist.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.advisor.exceptions.DBException;
import cn.tradewin.advisor.persist.mapper.VacationMapper;
import cn.tradewin.advisor.persist.model.Vacation;
import cn.tradewin.advisor.persist.model.VacationExample;
import cn.tradewin.advisor.persist.services.VacationService;

public class VacationServiceImpl implements VacationService {

private final SqlSessionFactory sqlSessionFactory;
	
	public VacationServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public int addVaction(Vacation vacation) throws DBException {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			VacationMapper mapper = session.getMapper(VacationMapper.class);
			int iCount = mapper.insert(vacation);
			if (iCount < 0) {
				session.rollback();
				return iCount;
			}
			session.commit();
			return  iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
	
	@Override
	public List<Vacation> listSelfVacations(String userid) throws DBException {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			VacationMapper mapper = session.getMapper(VacationMapper.class);
			VacationExample example = new VacationExample();
			example.createCriteria().andAccountIdEqualTo(userid);
			return mapper.selectByExample(example);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<Vacation> listAllVacations() throws DBException {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			VacationMapper mapper = session.getMapper(VacationMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int getMaxId(String account) throws DBException {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			VacationMapper mapper = session.getMapper(VacationMapper.class);
			VacationExample example = new VacationExample();
			example.createCriteria().andAccountIdEqualTo(account);
			return mapper.countByExample(example)+1;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	
}
